<template>
  <div>
    <div class="flex flex-col items-center justify-center w-full gap-3 mt-3 upload-txt">
      <h3 class="scroll-m-20 text-2xl font-semibold tracking-tight">文献翻译</h3>
      <p class="text-sm text-muted-foreground">将你的 PDF 翻译成一篇结构化的笔记</p>
    </div>
    <div class="upload-parent">
      <div class="flex flex-col gap-2">
        <div :class="dialogPage ? '' : 'reading-page'">
          <div class="relative" v-loading="loading">
            <el-upload
              style="width: 100%"
              class="upload-demo"
              drag
              :show-file-list="false"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleMainFileChange"
              :auto-upload="false"
              :accept="'.pdf,'"
            >
              <div style="display: inline-block">
                <svg xmlns="http://www.w3.org/2000/svg" width="126" height="96" fill="none" viewBox="0 0 126 96"><g filter="url(#filter0_d_48259_24903)"><rect width="45.672" height="61.719" x="11.145" y="22.624" fill="#fff" rx="6" transform="rotate(-12 11.145 22.624)"></rect><rect width="44.872" height="60.919" x="11.619" y="22.932" stroke="#E4E9EC" stroke-width="0.8" rx="5.6" transform="rotate(-12 11.619 22.932)"></rect></g><rect width="24.151" height="2.683" x="24.536" y="34.015" fill="#D2DBDF" rx="1.342" transform="rotate(-12 24.536 34.015)"></rect><rect width="24.151" height="2.683" x="26.211" y="41.889" fill="#D2DBDF" rx="1.342" transform="rotate(-12 26.21 41.889)"></rect><rect width="24.151" height="2.683" x="27.887" y="49.764" fill="#D2DBDF" rx="1.342" transform="rotate(-12 27.887 49.764)"></rect><rect width="16.101" height="2.683" x="33.501" y="56.802" fill="#D2DBDF" rx="1.342" transform="rotate(-12 33.501 56.802)"></rect><g filter="url(#filter1_d_48259_24903)"><rect width="45.672" height="61.719" x="70.181" y="13.134" fill="#fff" rx="6" transform="rotate(12 70.18 13.134)"></rect><rect width="44.872" height="60.919" x="70.489" y="13.608" stroke="#E4E9EC" stroke-width="0.8" rx="5.6" transform="rotate(12 70.489 13.608)"></rect></g><rect width="24.151" height="2.683" x="77.784" y="28.984" fill="#D2DBDF" rx="1.342" transform="rotate(12 77.784 28.984)"></rect><rect width="24.151" height="2.683" x="76.109" y="36.859" fill="#D2DBDF" rx="1.342" transform="rotate(12 76.11 36.86)"></rect><rect width="24.151" height="2.683" x="74.442" y="44.733" fill="#D2DBDF" rx="1.342" transform="rotate(12 74.442 44.733)"></rect><rect width="16.101" height="2.683" x="76.703" y="53.446" fill="#D2DBDF" rx="1.342" transform="rotate(12 76.703 53.446)"></rect><g filter="url(#filter2_d_48259_24903)"><path fill="#E4E9EC" stroke="#D2DBDF" stroke-linejoin="round" stroke-width="0.8" d="M69.1 30.674V11.001l19.063 19.804-19.062-.13z"></path><path fill="#fff" stroke="#D2DBDF" stroke-width="0.8" d="M44.3 11.275c-2.332.67-4.153 2.138-5.306 4.316-1.1 2.059-1.009-.761-1.009 28.985 0 25.3.013 26.467.236 27.214.878 2.86 3.079 5.142 5.79 6.007l.918.289h36.29l.917-.289c2.699-.852 4.913-3.16 5.79-6.007.223-.747.236-1.744.236-20.919V30.804l-9.524-.104-9.538-.027V11l-11.948.013c-11.437 0-12 .013-12.852.262z"></path><path fill="#647A84" d="M47.38 59.427V47.352h4.988c.904 0 1.684.176 2.34.53.661.35 1.17.84 1.528 1.468.358.625.537 1.353.537 2.182 0 .833-.183 1.563-.549 2.188a3.678 3.678 0 01-1.55 1.444c-.673.342-1.47.513-2.394.513h-3.078v-2.3h2.535c.44 0 .808-.076 1.103-.23.298-.153.524-.367.678-.642.153-.28.23-.604.23-.973 0-.373-.077-.696-.23-.967a1.544 1.544 0 00-.678-.637c-.299-.15-.667-.224-1.103-.224h-1.439v9.723H47.38zM62.741 59.427h-4.463V47.352h4.457c1.23 0 2.29.241 3.178.725a4.957 4.957 0 012.064 2.075c.483.9.725 1.977.725 3.231 0 1.258-.242 2.34-.725 3.243a4.957 4.957 0 01-2.058 2.082c-.892.48-1.951.719-3.178.719zm-1.545-2.488h1.433c.676 0 1.248-.114 1.716-.342.472-.232.827-.608 1.067-1.126.244-.523.366-1.219.366-2.088 0-.868-.122-1.56-.366-2.075-.244-.519-.603-.892-1.079-1.12-.472-.232-1.053-.348-1.745-.348h-1.392v7.099zM70.473 59.427V47.352h8.243v2.37H73.39v2.476h4.8v2.376h-4.8v4.853h-2.918z"></path></g><defs><filter id="filter0_d_48259_24903" width="79.275" height="91.636" x="0.26" y="4.243" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"></feColorMatrix><feOffset dy="2"></feOffset><feGaussianBlur stdDeviation="6"></feGaussianBlur><feComposite in2="hardAlpha" operator="out"></feComposite><feColorMatrix values="0 0 0 0 0.823529 0 0 0 0 0.858824 0 0 0 0 0.87451 0 0 0 0.7 0"></feColorMatrix><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_48259_24903"></feBlend><feBlend in="SourceGraphic" in2="effect1_dropShadow_48259_24903" result="shape"></feBlend></filter><filter id="filter1_d_48259_24903" width="79.275" height="91.636" x="46.464" y="4.249" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"></feColorMatrix><feOffset dy="2"></feOffset><feGaussianBlur stdDeviation="6"></feGaussianBlur><feComposite in2="hardAlpha" operator="out"></feComposite><feColorMatrix values="0 0 0 0 0.823529 0 0 0 0 0.858824 0 0 0 0 0.87451 0 0 0 0.7 0"></feColorMatrix><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_48259_24903"></feBlend><feBlend in="SourceGraphic" in2="effect1_dropShadow_48259_24903" result="shape"></feBlend></filter><filter id="filter2_d_48259_24903" width="74.98" height="91.887" x="25.583" y="0.6" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"></feColorMatrix><feOffset dy="2"></feOffset><feGaussianBlur stdDeviation="6"></feGaussianBlur><feComposite in2="hardAlpha" operator="out"></feComposite><feColorMatrix values="0 0 0 0 0.823529 0 0 0 0 0.858824 0 0 0 0 0.87451 0 0 0 0.7 0"></feColorMatrix><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_48259_24903"></feBlend><feBlend in="SourceGraphic" in2="effect1_dropShadow_48259_24903" result="shape"></feBlend></filter></defs></svg>
              </div>
              <div class="el-upload__text" v-show="!fileName">
                <p class="mb-1.5 text-md font-medium upload-txt">将文件拖放到此处，或点击选择文件</p>
                <p class="upload-txt text-xs">一个文件，大小不超过 50 MB</p>
              </div>
              <div class="el-upload__text" v-show="fileName">
                <p class="mb-1.5 text-md font-medium upload-txt">{{fileName}}</p>
                <p class="text-xs" style="margin-top: 10px"><el-icon style="margin-right: 2px"><Refresh /></el-icon>
                  重新选择</p>
              </div>
              <div style="height: 68px">
                <el-button class="upload-btn" v-show="!fileName">
                  <el-icon style="margin-right: 10px"><Upload /></el-icon>
                  选择文件
                </el-button>
                <!-- <el-button class="refresh-btn" v-show="fileName" style="margin-left: -130px">
                  <el-icon style="margin-right: 10px"><Refresh /></el-icon>
                  重新选择
                </el-button> -->
              </div>
              <template #tip>
                <div class="el-upload__tip upload-txt" style="text-align: center; margin-top: 20px">
                  文件解析可能需要三分钟左右。暂不支持扫描件识别。
                </div>
              </template>
            </el-upload>
            <div class="file-operate">
              <el-select class="model-select" v-model="optionsVal" placeholder="请选择模式" v-show="fileName">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button class="submit-btn" @click="submitBtn" v-show="fileName">
                <el-icon style="margin-right: 10px"><Check /></el-icon>
                开始解析
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
  import { useRouter } from 'vue-router'
  import { watch, ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { translateSingle, fileCheck } from '@/api/user'
  // 引入pdfjs
  import * as pdfjsLib from 'pdfjs-dist'

  // 设置 PDF.js workerSrc 使用 import.meta.url 确保正确加载
  pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.mjs',
    import.meta.url
  ).toString()
  
  const props = defineProps(['dialogPage']) 
  const router = useRouter()

  const loading = ref(false);

  const maxSize = ref(50);  // 最大50M
  const fileName = ref(null);
  const fileValue = ref(null);
  const filePage = ref(0);

  const options = ref([
    {
      value: 0,
      label: '速读模式：1积分/页'
    },
    {
      value: 1,
      label: '精读模式：5积分/页'
    },
    {
      value: 2,
      label: '研读模式：10积分/页'
    }
  ]);

  const optionsVal = ref(0);

  const handleMainFileChange = (file) => {
    console.log(file);
    if (file.size > maxSize.value * 1024 * 1024) {
      ElMessage.warning(`请选择小于${maxSize.value}M的文件`)
    } else {
      fileValue.value = file.raw
      fileName.value = file.name
      
      // 使用pdfjs获取PDF页数
      // getPdfPageCount(file.raw)
    }
  }
  
  // 使用标准的 pdfjs 方法，利用已配置的 workerSrc
  const getPdfPageCount = (file) => {
    console.log('开始处理文件:', file.name)
    filePage.value = 0;
    // 先尝试直接显示一个alert确认函数被调用
    // alert('文件已选择，正在分析页数...')
    
    try {
      // 创建文件读取器
      const fileReader = new FileReader()
      
      fileReader.onload = function(event) {
        console.log('文件读取完成')
        try {
          // 尝试使用标准方法获取页数
          const data = event.target.result
          
          // 使用已配置的workerSrc解析PDF
          const loadingTask = pdfjsLib.getDocument({
            data: new Uint8Array(data)
          });
          
          loadingTask.promise.then(function(pdf) {
            console.log('PDF解析成功')
            const pageCount = pdf.numPages
            console.log('PDF页数:', pageCount)
            // 显示页数
            filePage.value = pageCount;
            submitFn();
            // alert(`上传的PDF文件共有 ${pageCount} 页`)
          }).catch(function(error) {
            loading.value = false
            console.error('PDF解析错误:', error)
            ElMessage.error('解析PDF文件失败，请尝试其他文件');
          })
        } catch (error) {
          loading.value = false
          console.error('处理文件内容失败:', error)
          ElMessage.error('处理文件内容失败: ' + error.message)
        }
      }
      
      fileReader.onerror = function() {
        loading.value = false
        console.error('文件读取失败')
        ElMessage.error('文件读取失败')
      }
      
      // 开始读取文件
      console.log('开始读取文件内容')
      fileReader.readAsArrayBuffer(file)
    } catch (error) {
      loading.value = false
      console.error('获取PDF页数失败:', error)
      ElMessage.error('获取PDF页数失败: ' + error.message)
    }
  }

  const handleExceed = (file, uploadFiles) => {
    if (file[0].size > maxSize.value * 1024 * 1024) {
      ElMessage.warning(`请选择小于${maxSize.value}M的文件`)
    } else {
      fileValue.value = file[0]
      fileName.value = file[0].name
    }
  }

  const submitBtn = () => {
    loading.value = true
    getPdfPageCount(fileValue.value);
  }

  const submitFn = async ()=>{
    if (!filePage.value) {
      loading.value = false;
      ElMessage.error('文件解析失败，请重新选择');
      return false;
    }
    const params = {
      pages: filePage.value,
      modelType: optionsVal.value
    };
    let res = await fileCheck(params)
    if(res.code == 200 && res.data){
      console.log('积分够');
    } else {
      loading.value = false;
      ElMessage.error('积分不够，请先充值');
      return false;
    }
    try {
      let formData = new FormData();
      formData.append('file', fileValue.value);
      formData.append('modelType', optionsVal.value);
      let res = await translateSingle(formData)
      if(res.code == 200){
          loading.value = false
          router.push('/record')
      } else {
        loading.value = false;
        ElMessage.error(res.message);
      }
    } catch (error) {
      loading.value = false;
      ElMessage.error(error);
    }
  }

</script>
<style scoped>
.upload-parent {
  padding: 24px 50px;
}
.upload-txt {
  color: var(--txt-color);
}
.refresh-btn {
  height: 38px;
  border-radius: 6px;
  margin-top: 30px;
  border-color: #aaa
}
.refresh-btn:hover {
  color: var(--primary);
  border-color: var(--button-hover-border-color);
}
.upload-btn, .submit-btn {
  height: 38px;
  border-radius: 6px;
  margin-top: 30px;
  color: var(--button-text-color);
  background-color: var(--button-bg-color);
  border-color: var(--button-bg-color);
  /* margin-bottom: 20px; */
}
.upload-btn:hover, .submit-btn:hover {
  background-color: var(--button-hover-bg-color);
  border-color: var(--button-hover-border-color);
}
::v-deep .el-upload-dragger {
  /* padding-bottom: 80px; */
  background: var(--menu-background);
  border: 1px dashed var(--item-border);
}
::v-deep .el-upload-dragger:hover {
  border-color: var(--active-border);
}
.file-operate {
  display: inline-block;
  position: absolute;
  bottom: 83px;
  left: 50%;
  margin-left: -122px;
}
.submit-btn {
  float: right;
  margin-top: 0;
  /* position: absolute;
  left: 330px;
  bottom: 95px; */
}
.model-select {
  width: 112px;
  height: 38px;
  float: left;
  border-radius: 6px;
  margin-right: 20px;
}
::v-deep .el-select__wrapper {
  height: 38px;
  border-radius: 6px;
}
.reading-page {
  width: 672px;
  padding: 24px;
  border: 1px solid var(--border);
  border-radius: 20px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
::v-deep .el-loading-mask {
  background: var(--menu-background-all);
}
</style>
